package drds.global_transaction.common.thread;

import io.netty.util.concurrent.FastThreadLocalThread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedThreadFactory implements ThreadFactory
{
	private final AtomicInteger counter = new AtomicInteger(0);
	private final String prefix;
	private final int totalSize;
	private final boolean daemon;

	public NamedThreadFactory(String prefix, int totalSize)
	{
		this(prefix, totalSize, true);
	}

	public NamedThreadFactory(String prefix, int totalSize, boolean daemon)
	{
		this.prefix = prefix;
		this.daemon = daemon;
		this.totalSize = totalSize;
	}

	@Override
	public Thread newThread(Runnable runnable)
	{
		String threadName = prefix + "_" + counter.incrementAndGet();
		if (totalSize > 1)
		{
			threadName += "_" + totalSize;
		}
		Thread thread = new FastThreadLocalThread(runnable, threadName);

		thread.setDaemon(daemon);
		if (thread.getPriority() != Thread.NORM_PRIORITY)
		{
			thread.setPriority(Thread.NORM_PRIORITY);
		}
		return thread;
	}
}
